package com.highbury5.blog.util.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class SingleRedisComponent implements AbstractRedisComponent{

    private static JedisPool jedisPool;

    public SingleRedisComponent(){
        init();
    }

    /**
     * 初始化redis连接池
     */
    private static void init(){
        //jedisPool = new JedisPool("redis://a:testcase@10.14.55.209:6379/1");
        jedisPool = new JedisPool("redis://a:testcase@47.107.164.148:6379/1");
    }

    /**
     * 向对应的zset中元素score加1,返回最新score
     */
    @Override
    public double zincrby(String key ,String value){
        Jedis jedis = jedisPool.getResource();
        double result = jedis.zincrby(key,1,value);
        jedis.close();
        return result;
    }

    @Override
    public Map<String,Double> zrevrange(String key ,int start,int end){
        Jedis jedis = jedisPool.getResource();
        Set<Tuple> set =  jedis.zrevrangeWithScores(key,start,end);
        Map<String,Double> map = new LinkedHashMap();
        for(Tuple tuple : set){
            map.put(tuple.getElement(),tuple.getScore());
        }
        jedis.close();
        return map;
    }

    @Override
    public String get(String key){
        Jedis jedis = jedisPool.getResource();
        String value = jedis.get(key);
        jedis.close();
        return value;
    }


    @Override
    public Long incr(String key){
        Jedis jedis = jedisPool.getResource();
        Long value = jedis.incr(key);
        jedis.close();
        return value;
    }

}
